package com.uniknow.app.oauth.qq;

import java.io.File;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.widget.ImageView;
import android.widget.TextView;

import com.uniknow.app.AppConfig;
import com.uniknow.app.AppContext;
import com.uniknow.app.util.ImageUtils;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
/**
 * Tencent帮助类，包含了对Tencnet部分方法的简单的封装
 * @author lianjiao
 * 2014-05-15
 */
public class TencentHelper {
	private static TencentHelper tencentHelper = null;
	private static Context mContext;
	
	public static String TencentQQKeyUserName = "nickname";
	public static String TencentQQKeyUserPhotoURL = "figureurl_qq_2";
	public static String TencentQQKeyOpenId = "openid";
	public static String TencentQQKeyExpiresIn = "expires_in";
	public static String TencentQQKeyAccessToken = "access_token";
	
	private Tencent mTencent;//loginWithOEM 会用到
	private UserInfo mInfo;
	
	private TencentHelper(Context context){
		mContext = context;
		AppContext.QQAuth = QQAuth.createInstance(Constants.APP_ID, AppContext.getInstance());
		mTencent = Tencent.createInstance(Constants.APP_ID, mContext);
	}
	
    public Tencent getmTencent() {
		return mTencent;
	}

	public static synchronized TencentHelper getInstance(Context context){
    	if(tencentHelper==null){
			tencentHelper = new TencentHelper(context);
		}else{
			mContext = context;
		}
    	return tencentHelper;
    }
	
	/**
	 * <h1>绑定到QQ，并且获取用户信息</h1>
	 * <p>跳转到绑定界面，用户授权后，获取相应信息，保存在配置文件中。并且获取用户信息，写QQ UserName到当前传入的TextView对象中。</p>
	 * @param textView 需要显示QQ昵称的TextView控件
	 */
	public void BindingQQ(final TextView textView){
		IUiListener listenerLogin = new BaseUiListener((Activity) mContext){

			@Override
			protected void doComplete(JSONObject values) {
				super.doComplete(values);
				JSONObject json = (JSONObject)values;
				try {
					if(json.has(TencentQQKeyOpenId)){
						AppConfig.TencentOpenId = json.getString(TencentQQKeyOpenId);
					}
					if(json.has(TencentQQKeyExpiresIn)){
						AppConfig.TencentExpiresIn = json.getString(TencentQQKeyExpiresIn);					
					}
					if(json.has(TencentQQKeyAccessToken)){
						AppConfig.TencentAccessToken = json.getString(TencentQQKeyAccessToken);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				//写入SharedPreferences
				SharedPreferences preferences = mContext.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
				Editor editor = preferences.edit();
				// 存入数据					
				editor.putString("TencentOpenId", AppConfig.TencentOpenId);
				editor.putString("TencentExpiresIn", AppConfig.TencentExpiresIn);
				editor.putString("TencentAccessToken", AppConfig.TencentAccessToken);
				// 提交修改
				editor.commit();
				GetQQUserInfo(textView,null);
			}
			@Override
			public void onError(UiError e) {
				super.onError(e);
				textView.setText("Error");
			}
			@Override
			public void onCancel() {
				super.onCancel();
				textView.setText("Cancel");
			}
			
		};
		if(AppContext.QQAuth!=null){
			if(AppContext.QQAuth.isSessionValid()){
				AppContext.QQAuth.logout(mContext);
			}
		}else{
			AppContext.QQAuth = QQAuth.createInstance(Constants.APP_ID, AppContext.getInstance());
		}
		AppContext.QQAuth.login((Activity) mContext, "all", listenerLogin);
		
	}
	/**
	 * <h1>解除绑定到QQ</h1>
	 * <p>删除SharedPreferences中QQAuthUserName和token等信息， 并且置空AppContext.QQAuth </p>
	 * @param mContext
	 * @param uname 需要显示QQ昵称的TextView控件
	 * @return boolean
	 */
	public boolean UnBindingQQ(){
		//写入SharedPreferences
		SharedPreferences preferences = mContext.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		Editor editor = preferences.edit();
		// 存入数据
		editor.putString("TencentOpenId", "");
		editor.putString("TencentExpiresIn", "0");
		editor.putString("TencentAccessToken", "");
		// 提交修改
		editor.commit();
		if(AppContext.QQAuth!=null&&AppContext.QQAuth.isSessionValid()){
			AppContext.QQAuth.logout(mContext);
			AppContext.QQAuth = null;
		}
		return true;
	}
	/**
	 * <h1>检测是否已经绑定QQ</h1>
	 * <p>通过读取配置文件信息，监测是否绑定了用户QQ帐号</p>
	 * @param mContext
	 * @return boolean
	 */
	public static boolean CheckBindingQQ(Context context){
		SharedPreferences preferences = context.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
		String open_id = preferences.getString("TencentOpenId", "");
		if(open_id.length()>2){
			return true;
		}else{
			return false;
		}
	}
	public boolean CheckBindingQQ(){
		return CheckBindingQQ(mContext);
	}
	/**
	 * <h1>检测认证信息是否有效</h1>
	 * <p>检测当前全局变量中的AppContext是否是登陆后的有效QQAuth,否则可以进行loginWithOEM登录操作等方法。</p>
	 * @return
	 */
	public boolean CheckQQAuthIsValid(){
		if(AppContext.QQAuth!=null&&AppContext.QQAuth.isSessionValid()){
			return true;
		}else{
			return false;
		}
	}
	/**
	 * <h1>获取QQ用户基本信息</h1>
	 * <p>从腾讯数据源，获取用户基本信息，返回一个json对象。并且保存用户基本信息（username、userphotourl）到SharedPreferences配置文件中，如果需要展示ImageView，那么展示后会保存用户Q图像到ImageCach文件夹里</p>
	 * @param textView 用户Q名展示view
	 * @param imageView 用户Q图像展示View
	 */
	public void GetQQUserInfo(final TextView textView,final ImageView imageView){
		if(AppContext.QQAuth!=null&&AppContext.QQAuth.isSessionValid()){
			IUiListener listenerUserInfo = new BaseUiListener((Activity) mContext) {
				@Override
				protected void doComplete(JSONObject values) {
					super.doComplete(values);
					JSONObject json = (JSONObject)values;
					if(json!=null&&json.has(TencentHelper.TencentQQKeyUserName)){
						try {
							AppConfig.QQAuthUserName = json.getString(TencentHelper.TencentQQKeyUserName);
							AppConfig.QQAuthUserPhotoURL = json.getString(TencentHelper.TencentQQKeyUserPhotoURL); 
						} catch (JSONException e) {
							e.printStackTrace();
						}
						SharedPreferences preferences = mContext.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
						Editor editor = preferences.edit();
						editor.putString("QQAuthUserName", AppConfig.QQAuthUserName);
						editor.putString("QQAuthUserPhotoURL", AppConfig.QQAuthUserPhotoURL);
						editor.commit();
						textView.setText(AppConfig.QQAuthUserName);
						if(imageView!=null){
							Bitmap bitmap = Util.getbitmap(AppConfig.QQAuthUserPhotoURL);
							imageView.setImageBitmap(bitmap);
							try {
								ImageUtils.saveImageToSD(AppConfig.FOLDER_IMG_CACHE+File.separator+AppConfig.QQAuthUserPhotoURL,bitmap,100);
							} catch (IOException e) {
								System.out.println("保存用户QQ图像到"+AppConfig.FOLDER_IMG_CACHE+"文件夹失败！！");
								e.printStackTrace();
							}
						}
						
					}
				}
			};
			mInfo = new UserInfo(mContext, AppContext.QQAuth.getQQToken());
			mInfo.getUserInfo(listenerUserInfo);
		}
	}

}
